<template>
  <panel :title="title">
    <el-form ref="addForm" :model="addForm" label-width="80px" class="add-form" :rules="rules">
      <el-form-item label="账号" prop="account">
        <el-input v-model="addForm.account"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="addForm.password" type="password"></el-input>
      </el-form-item>

      <el-form-item label="用户组" prop="userGroup">
        <el-select v-model="addForm.userGroup" placeholder="请选择用户组">
          <el-option value="超级管理员"></el-option>
          <el-option value="普通管理员"></el-option>
        </el-select>
      </el-form-item>

        <el-form-item>
          <el-button type="warning" @click="submitForm">添加</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
    </el-form>
  </panel>
</template>

<script>
import Panel from "@/components/panel/Panel.vue";
import { checkAccountReg, checkPwdReg, accountvalidator } from '@/utils/tools';

import { addAccount } from '@/api/user'
export default {
  components: {
    Panel,
  },
  data() {
    // 验证账号
    const checkAccount = (rule, value, callback) => {
      accountvalidator(rule, value, callback);
    } 

    // 验证密码
    const checkPwd = (rule, value, callback) => {
      // 需要验证的是 不能为空, 正则表达式匹配还有长度
      if (!value) {
        callback(new Error('请输入密码')) 
      } else if(!checkPwdReg(value)) {
        callback(new Error('6 ~ 12 位,数字/字母/下划线/-'))
      } else {
        callback()
      }
    } 


    return {
      title: "添加账号",
      addForm: {
        account: "",
        password: "",
        userGroup: "",
      },
      rules: {
        account: { required: true, validator: checkAccount, trigger: 'blur'},
        password: {required: true, validator: checkPwd, trigger: 'blur'},
        userGroup: {required: true, message: '请选择用户组', trigger: 'change'}

      }
    };
  },
  methods: {
    submitForm() {
      // valid形参是表单验证的布尔值
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          try {
            let res = await addAccount(this.addForm);
            let {code} = res.data
            if (code === 0) {
              this.$router.push('/account/account-list')
            }
          }catch(err) {
            console.log(err)
          }

        } else {
          return
        }
      })
    },
    reset() {
      this.$refs.addForm.resetFields()
    }
  }
};
</script>

<style lang="less" scoped>
.add-form {
  /deep/ .el-input__inner {
    width: 200px;
  }
}

</style>